package org.nicocube.airain.common.client.table;

import java.util.LinkedList;
import java.util.List;

import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Widget;

public class TableOfItem {

	/**
	 * Default CSS class name for {@link TableOfItem} 
	 */
	private static final String DaGrid = "daGrid";

	/**
	 * The {@link TableHeader} object associated with this table of item   
	 */
	private TableHeader header;

	/**
	 * The CSS class name applied to the rendered {@link TableOfItem}
	 */
	private String className;

	/**
	 * The secundary CSS class name applied to the rendered {@link TableOfItem}
	 */
	private String additionnalClassName;

	private List<Item> rows;

	private FlexTable rendering;

	private String noData;

	private int rowToClear;

	public TableOfItem() {
		this(null);
	}

	public TableOfItem(TableHeader header) {
		this(header,DaGrid,null);
	}

	public TableOfItem(TableHeader header,String className,String additionnalClassName) {
		this.className = className;
		this.header = header;
		this.rows = new LinkedList<Item>();
		this.additionnalClassName=additionnalClassName;
		rowToClear = 0;
	}

	public TableOfItem addRow(Item row) {
		rows.add(row);
		row.setRank(rows.size()-1);
		return this;
	}

	public void delRow(Item row) {
		if (row.getRank() < rows.size()) {
			rows.remove(row.getRank());
			for (int i = row.getRank(); i < rows.size();i++) {
				Item r = rows.get(i);
				r.setRank(r.getRank()-1);
			}
		}
		rowToClear++;
	}

	public Widget render() {
		if (rendering == null) {
			rendering = new FlexTable();
			rendering.setCellPadding(0);
			rendering.setCellSpacing(1);
			rendering.setStylePrimaryName(className);
			if (additionnalClassName!=null) rendering.addStyleName(additionnalClassName);
		}
		if (header != null) header.render(rendering);
		int r=1;
		if (rows.size() > 0) {
			for (Item row : rows) {
				row.render(r,rendering);
				r++;
			}
		}

		if (rowToClear > 0) {
			for (;rowToClear > 0 ; rowToClear--,r++) {
				for (int i=0;i<header.size();i++)
					rendering.clearCell(r, i);
			}
		}

		if (rows.isEmpty()) {
			rendering.setText(1, 0, noData);
		}

		return rendering;
	}

	public TableOfItem noData(String noData) {
		this.noData = noData;
		return this;
	}

}
